import socket
import eventlet
from io import BytesIO
from apps.tcpserver.proto.utils import btoi, itob
from apps.tcpserver.urls import event_handles
from apps.tcpserver.connection import Message

class HandleUDPConnect:

    conns = dict()

    def __call__(self, conn: socket.socket):
        while True:
            msg, addr = self.recv(conn)
            print(msg.hex())
            print(msg.msgtyp)
            handle = event_handles.get(itob(msg.msgtyp))
            print(handle)
            
            if handle:
                eventlet.spawn_n(handle,None,msg)
            eventlet.sleep()

    def recv(self, conn: socket.socket):
        data, addr = conn.recvfrom(1024 * 8)

        data: BytesIO = BytesIO(data)

        head = data.read(2)
        if head == b'':
            return None, None
        payload_length = data.read(2)
        payload_length = btoi(payload_length)
        payload = data.read(payload_length)
        (
            msgid,
            total_package,
            current_package,
            msg_type,
            body
        ) = (
            payload[:4],
            payload[4:6],
            payload[6:8],
            payload[8:9],
            payload[9:]
        )
        sign = data.read(1)
        end = data.read(2)
        assert len(payload) == payload_length, OSError('read faid')
        msg =Message(
                        content=msg_type+body,
                        msgid=msgid,
                        conn=None
                    )
        msg.content = body
        return msg, addr
